﻿using System;
using System.Text;
using System.Web;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;
namespace Clipping.SearchUrlConstructors
{
	public class YahooNewsUrlConstructor : ISearchUrlConstruct
	{
		private Encoding _urlEncoding = Encoding.UTF8;
		public Uri ConstructUrl(SearchObject searchObj)
		{
			//Contract.Requires(searchObj != null);
			if (searchObj is PeriodSearchObject)
			{
				PeriodSearchObject so=searchObj as PeriodSearchObject;
				string queryOption=string.Format("&x=0-2-{0}-{1}",getSearchTypeCode(searchObj.SearchType),getPeroidCode(so.SearchPeriod));
				string url = string.Format("{0}{1}{2}", "http://news.yahoo.cn/s?q=", HttpUtility.UrlEncode(searchObj.Keyword, this._urlEncoding), queryOption);
				return new Uri(url);
			}
			else if (searchObj is TimespanSearchObject)
			{
				TimespanSearchObject so = searchObj as TimespanSearchObject;
				TimeSpan ts = DateTime.Now - so.StartTime;
				string queryOption = string.Format("&x=0-2-{0}-{1}", getSearchTypeCode(searchObj.SearchType), ts.Days+1);
				string url = string.Format("{0}{1}{2}", "http://news.yahoo.cn/s?q=", HttpUtility.UrlEncode(searchObj.Keyword, this._urlEncoding), queryOption);
				return new Uri(url);
			}
			else
			{
				return null;
			}
		}

		private int getSearchTypeCode(SearchType searchType)
		{
			if (searchType == SearchType.SearchInTitle)
			{
				return 1;
			}
			else
			{
				return 2;
			}
		}
		
		private int getPeroidCode(SearchPeriod period)
		{
			switch (period)
			{
				case SearchPeriod.全部时间:
					return 0;
				case SearchPeriod.最近1年:
					return 365;
				case SearchPeriod.最近1天:
					return 1;
				case SearchPeriod.最近1月:
					return 30;
				case SearchPeriod.最近1周:
					return 7;
				case SearchPeriod.最近2天:
					return 2;
				case SearchPeriod.最近2月:
					return 60;
				case SearchPeriod.最近3天:
					return 3;
				case SearchPeriod.最近3月:
					return 90;
				default:
					return 0;
			}






		}

		public Uri ConstructAbsoluteUrl(Uri baseUri, string url)
		{
			return UriHelper.ConstructAbsoluteUrl(baseUri, url);
		}
	}
}
